{% extends 'wancake/base_nav_frame.html' %}
{% load staticfiles %}
{% block css %}
  <link rel="stylesheet" href="{% static 'wancake/css/epg_syncer.css' %}" />
{% endblock %}
{% block content %}

  <div class="wb-button-set">
    <button type="button" class="btn btn-default" id="syncer-btn-launch-sync">同步</button>
    <button type="button" class="btn btn-danger" id="syncer-btn-reset">重置</button>
  </div>

  <div class="row">
    <div class="container col-sm-6 col-md-6 col-lg-6 col-xs-6">
      <div class="progress">
        <div class="progress-bar progress-bar-info progress-bar-striped active" role="progressbar"
             aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"
             id="wb-sync-progress-bar">
        </div>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="container col-sm-6 col-md-6 col-lg-6 col-xs-6">
      <div class="well well-lg" id="wb-sync-info-panel">
      </div>
    </div>
  </div>


{% endblock %}
{% block jsimport %}
  <script src="{% static 'wancake/js/wancake.js' %}"></script>
{% endblock %}
{% block jsscript %}
  <script type="text/javascript">
    $(document).ready(function(e) {

      var TABLE_NAME_MAP = {
        "order_record" : "order_record表"
        , "statis_category" : "statis_category表"
        , "sys_cp_products" : "sys_cp_products表"
        , "sys_organization" : "sys_organization表"
        , "user_cate_statis" : "user_cate_statis表"
        , "user_play_daily" : "user_play_daily表"
        , "user_play_detail" : "user_play_detail表"
        , "user_play_info" : "user_play_info表"
        , "user_play_total" : "user_play_total表"
        , "wanba_daily_order_stat" : "wanba_daily_order_stat表"
        , "wanba_daily_statis" : "wanba_daily_statis表"
        , "wanba_user_account" : "wanba_user_account表"
      };

      var completedTaskCount = 0;
      var TASK_COUNT = 12;

      var onCompleteATask = function(table, isOk) {
        var syncInfo = $("#wb-sync-info-panel").find("p[sync-table='"+ table +"']");
        var syncInfoResult = $(syncInfo).find(".wb-sync-info-result");
        if (isOk) {
          $(syncInfoResult).addClass("wb-sync-info-result-ok").text("完成");
        } else {
          $(syncInfoResult).addClass("wb-sync-info-result-fail").text("失败");
        }

        completedTaskCount++;
        var syncProgress = parseInt((parseFloat(completedTaskCount) / TASK_COUNT) * 100);
        $("#wb-sync-progress-bar").attr({
          "aria-valuenow" : syncProgress
          , "style" : "width: " + syncProgress + "%"
        });
      };

      var onStartSync = function() {

        $("#wb-sync-info-panel").empty();

        completedTaskCount = 0;
        var progressBar = $("#wb-sync-progress-bar");
        if ($(progressBar).hasClass("progress-bar-success")) {
          $(progressBar).removeClass("progress-bar-success")
              .addClass("progress-bar-info");
        }
        if (!$(progressBar).hasClass("progress-bar-striped")) {
          $(progressBar).addClass("progress-bar-striped");
        }
        if (!$(progressBar).hasClass("active")) {
          $(progressBar).addClass("active");
        }

        $(progressBar).attr({
          "aria-valuenow" : 0
          , "style" : "width: 0%"
        });
      };

      var onCompleteSync = function() {
        completedTaskCount = TASK_COUNT;

        var progressBar = $("#wb-sync-progress-bar");

        if ($(progressBar).hasClass("progress-bar-info")) {
          $(progressBar).removeClass("progress-bar-info")
              .addClass("progress-bar-success");
        }
        if ($(progressBar).hasClass("progress-bar-striped")) {
          $(progressBar).removeClass("progress-bar-striped");
        }
        if ($(progressBar).hasClass("active")) {
          $(progressBar).removeClass("active");
        }

        $(progressBar).attr({
          "aria-valuenow" : 100
          , "style" : "width: 100%"
        });

        var syncInfo = $("<p />")
            .addClass("wb-sync-info")
            .addClass("wb-sync-info-result")
            .addClass("wb-sync-info-result-ok")
            .text("同步完成");
        $("#wb-sync-info-panel").append(syncInfo);
      };

      var onStartCallback = function(from, to) {
        console.log("Start sync data from " + from + " to " + to);

        var syncInfo = $("<p />").attr({
              "sync-table" : from
            }).addClass("wb-sync-info")
            .text("同步" + TABLE_NAME_MAP[from]);
        var syncInfoResult = $("<span />").addClass("wb-sync-info-result");
        $(syncInfo).append(syncInfoResult);
        $("#wb-sync-info-panel").append(syncInfo);

      };

      var onDoneCallback = function(task, from, to, data) {
        console.log("Sync data from " + from + " to " + to + " done:)");

        onCompleteATask(from, true);

        task.resolve();
      };

      var onFailCallback = function(task, from, to, data) {
        console.log("Sync data from " + from + " to " + to + " fail:(");

        onCompleteATask(from, false);

        task.reject();
      };

      var syncTable = function(task, fromTable, toTable, idColName, onStart, onDone, onFail) {

        if (onStart) {
          onStart(fromTable, toTable)
        }

        $.ajax("./getepgsyncrecord", {
          type : "GET"
          , data : {
            table : toTable
          }
          , dataType : 'json'
          , success : function(json) {
            var lastId = json.data.last_id;

            $.ajax("http://218.83.169.39:7080/epgsync/getepgdata", {
              type : "GET"
              , data : {
                table : fromTable
                , fromid : lastId
                , idcolumnname : idColName
              }
              , dataType : 'json'
              , success : function(json) {
                if (json.resultCode && json.resultCode == 1) {
                  var data = json.data;
                  var resultList = data.resultList || [];
                  if (resultList.length > 0) {
                    var length = resultList.length;
                    var SIZE = 5000;
                    if (length <= SIZE) {
                      $.ajax("./syncepg", {
                        type : "POST"
                        , data : {
                          table : toTable
                          , rawIdColumnName : idColName
                          , epgData : JSON.stringify(resultList)
                        }
                        , dataType : "json"
                        , success : function(data) {
                          if (onDone) {
                            onDone(task, fromTable, toTable)
                          }
                        }
                        , error : function() {
                          if (onFail) {
                            onFail(task, fromTable, toTable)
                          }
                        }
                      });
                    } else {
                      var offset = 0;
                      $w.ajaxLooper("./syncepg", {
                            dataType : "json",
                            type : "POST",
                            data : {
                              table : toTable
                              , rawIdColumnName : idColName
                              , epgData : JSON.stringify(resultList.slice(offset, offset + SIZE))
                            }
                          })
                          .onSuccess(function(looper, data) {
                            if (offset + SIZE >= length) {
                              looper.done();
                            } else {
                              looper.again(data);
                            }
                          })
                          .onError(function(looper) {
                            if (onFail) {
                              onFail(task, fromTable, toTable)
                            }
                          })
                          .onAgain(function(looper, data) {
                            offset += SIZE;
                            var end = Math.min(offset + SIZE, length);
                            return {
                              data : {
                                table : toTable
                                , rawIdColumnName : idColName
                                , epgData : JSON.stringify(resultList.slice(offset, end))
                              }
                            };
                          })
                          .onDone(function() {
                            if (onDone) {
                              onDone(task, fromTable, toTable)
                            }
                          })
                          .start();
                    }

                  } else {
                    if (onDone) {
                      onDone(task, fromTable, toTable)
                    }
                  }
                }
              }
              , error : function() {
                if (onFail) {
                  onFail(task, fromTable, toTable)
                }
              }
            });
          }
          , error : function() {
            if (onFail) {
              onFail(task, fromTable, toTable)
            }
          }
        });
      };

      var resetTask = function(task, tableName) {
          $.ajax("./clearepg", {
                type : "GET"
                , dataType : "json"
                , data : {
                  table : tableName
                }
              })
              .done(function(data) {
                task.resolve();
              })
              .fail(function(data) {
                task.reject();
              });
      };

      $("#syncer-btn-launch-sync").click(function(e) {

        onStartSync();

        $w.asyncTask(function(task) {
                syncTable(task, "order_record", "EpgOrderRecord", "order_id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "statis_category", "EpgStatisCategory", "id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "sys_cp_products", "EpgSysCpProducts", "record_id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "sys_organization", "EpgSysOrganization", "id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "user_cate_statis", "EpgUserCateStatis", "id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "user_play_daily", "EpgUserPlayDaily", "daily_id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "user_play_detail", "EpgUserPlayDetail", "detail_id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "user_play_info", "EpgUserPlayInfo", "id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "user_play_total", "EpgUserPlayTotal", "id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "wanba_daily_order_stat", "EpgWanbaDailyOrderStat", "record_id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .then(function(task) {
                syncTable(task, "wanba_daily_statis", "EpgWanbaDailyStatis", "record_id",
                    onStartCallback, onDoneCallback, onFailCallback)
              })
            .done(function() {
                onCompleteSync();
            });

      });

      $("#syncer-btn-reset").click(function (e) {

        onStartSync();

        $w.asyncTask(function(task) {
              resetTask(task, "EpgOrderRecord");
            })
            .then(function(task) {
              resetTask(task, "EpgStatisCategory");
            })
            .then(function(task) {
              resetTask(task, "EpgSysCpProducts");
            })
            .then(function(task) {
              resetTask(task, "EpgSysOrganization");
            })
            .then(function(task) {
              resetTask(task, "EpgUserCateStatis");
            })
            .then(function(task) {
              resetTask(task, "EpgUserPlayDaily");
            })
            .then(function(task) {
              resetTask(task, "EpgUserPlayDetail");
            })
            .then(function(task) {
              resetTask(task, "EpgUserPlayInfo");
            })
            .then(function(task) {
              resetTask(task, "EpgUserPlayTotal");
            })
            .then(function(task) {
              resetTask(task, "EpgWanbaDailyOrderStat");
            })
            .then(function(task) {
              resetTask(task, "EpgWanbaDailyStatis");
            })
            .then(function(task) {
              resetTask(task, "EpgWanbaUserAccount");
            })
            .done(function() {
              onCompleteSync();
            });

      })
    });
  </script>
{% endblock %}